import  { useEffect, useRef } from 'react';
import type { YuqueEditorProps, EditorInstance } from './types';
import { DEFAULT_TOOLBAR_ITEMS } from './constants';
import './style.css';

declare global {
  interface Window {
    Doc: {
      createOpenEditor: (element: HTMLElement, config: any) => EditorInstance;
      toolbarItems: Record<string, any>;
    };
  }
}

export function YuqueEditor({
  className = '',
  style = {},
  defaultValue = '<p>欢迎使用编辑器</p>',
  onChange,
  config = {},
  onError
}: YuqueEditorProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  const editorInstanceRef = useRef<EditorInstance | null>(null);
  const isInitializedRef = useRef(false);

  useEffect(() => {
    if (isInitializedRef.current) return;

    const initEditor = async () => {
      if (!editorRef.current) return;

      try {
        if (!window.Doc) {
          throw new Error('请确保已加载并初始化 LakeX');
        }

        const { createOpenEditor, toolbarItems } = window.Doc;
        const toolbarConfig = DEFAULT_TOOLBAR_ITEMS.map(item =>
          item === '|' ? item : toolbarItems[item]
        );

        const editor = createOpenEditor(editorRef.current, {
          input: {},
          toc: true,
          toolbar: {
            items: toolbarConfig
          },
          ...config
        });

        editor.setDocument('text/lake', defaultValue);
        editor.on('contentchange', () => {
          const content = editor.getDocument('text/lake');
          onChange?.(content);
        });

        editorInstanceRef.current = editor;
        isInitializedRef.current = true;
      } catch (error) {
        console.error('编辑器初始化错误:', error);
        onError?.(error instanceof Error ? error : new Error(String(error)));
      }
    };

    initEditor();

    return () => {
      if (editorInstanceRef.current) {
        editorInstanceRef.current.destroy?.();
        editorInstanceRef.current = null;
        isInitializedRef.current = false;
      }
    };
  }, [config, onError]);

  useEffect(() => {
    if (editorInstanceRef.current && isInitializedRef.current) {
      const currentContent = editorInstanceRef.current.getDocument('text/lake');
      if (currentContent !== defaultValue) {
        editorInstanceRef.current.setDocument('text/lake', defaultValue);
      }
    }
  }, [defaultValue]);

  return (
    <div className={`yuque-editor ${className}`} style={{ height: '100%', ...style }}>
      <div ref={editorRef} className="ne-doc-major-editor" style={{ height: '100%', border: '1px solid #e8e8e8' }}></div>
    </div>
  );
} 